package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.config.CacheService;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.common.constants.message.HotArticleConstants;
import com.heima.common.constants.user.UserRelationConstants;
import com.heima.model.behavior.dtos.ReadBehaviorDto;
import com.heima.model.behavior.pojos.UpdateArticleMess;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {
    @Autowired
    CacheService cacheService;
    @Autowired
    KafkaTemplate kafkaTemplate;

    /**
     * 保存阅读行为
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult read(ReadBehaviorDto dto) {
        //参数校验
        if (dto == null || dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取登录人信息
        ApUser apUser = AppThreadLocalUtils.getUser();
        if (apUser == null) {
            return ResponseResult.okResult();
        }
        //第一次登陆设置初始值1
        if (dto.getCount() == 0) {
            dto.setCount(1);
        }
        //更新阅读次数
        String readBehaviorJson = (String) cacheService.hGet(UserRelationConstants.READ_LIST + apUser.getId(), dto.getArticleId().toString());
        if (StringUtils.isNotBlank(readBehaviorJson)) {
            ReadBehaviorDto readBehaviorDto = JSON.parseObject(readBehaviorJson, ReadBehaviorDto.class);
            dto.setCount(readBehaviorDto.getCount() + 1);
        }
        //保存
        cacheService.hPut(UserRelationConstants.READ_LIST + apUser.getId(), dto.getArticleId().toString(), JSON.toJSONString(dto));

        //*****kafka发送消息,实时计算热点分数******
        UpdateArticleMess mess = new UpdateArticleMess();
        mess.setArticleId(dto.getArticleId());
        mess.setType(UpdateArticleMess.UpdateArticleType.VIEWS);
        kafkaTemplate.send(HotArticleConstants.HOTARTICLE_SCORE_INPUT_TOPIC, JSON.toJSONString(mess));
        //****************

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
